package com.xframe.xdal.core.autofill.proc;

import com.xframe.xdal.core.autofill.IAutoFillBean;
import com.xframe.xdal.core.autofill.IAutoProc;
import com.xframe.xdal.core.util.StringUtil;

import java.util.Random;

public class RandomDefVal implements IAutoProc {
    Random rdm = new Random();


    @Override
    public Object getVal(IAutoFillBean autoFillBean, Object entity, Object val) {

        try {
            if (StringUtil.isEmpty(autoFillBean.getDefVal())) {
                return val;
            }

            String regex = ",";
            if(StringUtil.isNotEmpty(autoFillBean.getArgs())){
                regex = autoFillBean.getArgs();
            }
            String[] vals = autoFillBean.getDefVal().split(regex);
            if (vals == null || vals.length == 0) {
                return val;
            }
            int index = randomIndex(vals.length);
            return StringUtil.StringConvert(autoFillBean.getFieldType(), vals[index]);
        }catch (Exception e){
            e.printStackTrace();
            return val;
        }
    }


    private int randomIndex(int maxIndex){
        int val = Math.abs(rdm.nextInt());
        return val % maxIndex;
    }
}
